package com.platform.schedule.dynamic.service.impl;

import com.platform.schedule.dynamic.domain.DynamicScheduleInfo;
import com.platform.schedule.dynamic.service.DynamicScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 动态任务服务实现
 * <p>
 *
 * @author: WangYang
 * @date: 2018-01-05 16:35
 * @version: 1.0
 * @since 1.8
 */
public class DynamicScheduleServiceImpl implements DynamicScheduleService {

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public List<DynamicScheduleInfo> get() throws Exception {
        Map<String, DynamicScheduleTemplate> taskMap = applicationContext.getBeansOfType(DynamicScheduleTemplate.class);
        return taskMap.values().stream().map(item ->
                new DynamicScheduleInfo().setName(item.getName()).setCron(item.getCron())
        ).collect(Collectors.toList());
    }

    @Override
    public DynamicScheduleInfo get(String name) throws Exception {
        DynamicScheduleTemplate item = (DynamicScheduleTemplate) applicationContext.getBean(name);
        return new DynamicScheduleInfo().setName(item.getName()).setCron(item.getCron());
    }

    @Override
    public void updateCron(String name, String cron) throws Exception {
        DynamicScheduleTemplate item = (DynamicScheduleTemplate) applicationContext.getBean(name);
        item.setCron(cron);

    }
}
